package net.guerlab.smart.platform.user.api.autoconfig;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import net.guerlab.smart.platform.user.api.OperationLogApi;
import net.guerlab.smart.platform.user.api.feign.FeignOperationLogApi;
import net.guerlab.smart.platform.user.core.domain.OperationLogDTO;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author guer
 */
@Configuration
@AutoConfigureAfter(OperationLogApiLocalServiceAutoConfigure.class)
public class OperationLogApiFeignAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnMissingBean(OperationLogApi.class)
    public OperationLogApi operationLogApiFeignWrapper(FeignOperationLogApi api, ApplicationContext applicationContext,
            ObjectMapper objectMapper) {
        return new OperationLogApiFeignWrapper(api, applicationContext, objectMapper);
    }

    @AllArgsConstructor
    private static class OperationLogApiFeignWrapper implements OperationLogApi {

        private final FeignOperationLogApi api;

        private final ApplicationContext applicationContext;

        private final ObjectMapper objectMapper;

        @Override
        public void add(String operationContent, Long userId, Object... operationParams) {
            OperationLogDTO operationLog = new OperationLogDTO();
            operationLog.setApplicationName(applicationContext != null ?
                    applicationContext.getEnvironment().getProperty("spring.application.name") :
                    null);
            operationLog.setOperationContent(operationContent);
            try {
                operationLog.setOperationParams(objectMapper.writeValueAsString(operationParams));
            } catch (Exception ignored) {
            }
            operationLog.setUserId(userId);

            api.add(operationLog);
        }
    }

}
